package es.andresimon.portfolio.domain;

import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
import es.andresimon.portfolio.domain.Friend;

@Component
@Configurable
public class FriendDataOnDemand {

	private Random rnd = new java.security.SecureRandom();

	private List<Friend> data;

	public Friend getNewTransientFriend(int index) {
        es.andresimon.portfolio.domain.Friend obj = new es.andresimon.portfolio.domain.Friend();
        java.lang.String description = "description_" + index;
        if (description.length() > 100) {
            description  = description.substring(0, 100);
        }
        obj.setDescription(description);
        java.lang.String url = "url_" + index;
        if (url.length() > 100) {
            url  = url.substring(0, 100);
        }
        obj.setUrl(url);
        obj.setWeight(new Integer(index));
        return obj;
    }

	public Friend getSpecificFriend(int index) {
        init();
        if (index < 0) index = 0;
        if (index > (data.size() - 1)) index = data.size() - 1;
        Friend obj = data.get(index);
        return Friend.findFriend(obj.getId());
    }

	public Friend getRandomFriend() {
        init();
        Friend obj = data.get(rnd.nextInt(data.size()));
        return Friend.findFriend(obj.getId());
    }

	public boolean modifyFriend(Friend obj) {
        return false;
    }

	public void init() {
        data = es.andresimon.portfolio.domain.Friend.findFriendEntries(0, 10);
        if (data == null) throw new IllegalStateException("Find entries implementation for 'Friend' illegally returned null");
        if (!data.isEmpty()) {
            return;
        }
        
        data = new java.util.ArrayList<es.andresimon.portfolio.domain.Friend>();
        for (int i = 0; i < 10; i++) {
            es.andresimon.portfolio.domain.Friend obj = getNewTransientFriend(i);
            obj.persist();
            obj.flush();
            data.add(obj);
        }
    }
}
